export class BroadcastMessage {
  channel: BroadcastChannel;
  subscribers: Array<any>;
  constructor(channelName = 'CHANNEL') {
    this.channel = new BroadcastChannel(channelName);
    this.subscribers = [];

    this.channel.addEventListener('message', event => {
      for (const subscriber of this.subscribers) {
        subscriber(event.data);
      }
    });
  }

  subscribe(handler: Function) {
    this.subscribers.push(handler);
  }

  async publish(data: any) {
    await Promise.allSettled([this.channel.postMessage(data)]);
  }

  close() {
    this.channel.close();
  }
}
